package com.karson.zk.nativeapi.session;

import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  @title ZKSessionConnect
 *  @Description 恢复之前的会话
 *  @author Karson Wang
 *  @Date 2020/3/31 19:48
 *  @Copyright 2019-2020 
 */
public class ZKSessionConnect {

    final static Logger log = LoggerFactory.getLogger(ZKSessionConnect.class);

    public static final String zkServerPath = "zk1:2181,zk2:2181,zk3:2181";

    public static final Integer timeout = 5000;

    public static void main(String[] args) throws Exception {

        // 连接成功后会收到通知
        Watcher watcher = event -> log.warn("接受到watch通知：{}", event);

        ZooKeeper zk = new ZooKeeper(zkServerPath, timeout, watcher);

        log.warn("客户端开始连接zookeeper服务器...");

        SessionInfo sessionInfo = showState(zk, "连接状态：{}");

        log.warn("开始会话重连...");

        ZooKeeper zkSession = new ZooKeeper(zkServerPath, timeout, watcher, sessionInfo.getSessionId(), sessionInfo.getSessionPassword());

        showState(zkSession, "重新连接状态zkSession：{}");
    }

    private static SessionInfo showState(ZooKeeper zk, String msg) throws InterruptedException {
        while (true) {
            log.warn(msg, zk.getState());
            if (ZooKeeper.States.CONNECTED == zk.getState()) {
                SessionInfo sessionInfo = new SessionInfo(zk.getSessionId(), zk.getSessionPasswd());
                System.out.println("sessionId = " + sessionInfo.getSessionId() + ", sessionPassword = " + sessionInfo.getSessionPassword());
                return sessionInfo;
            }
            new Thread().sleep(50);
        }
    }
}
